package admin

import (
	"fmt"
	"go-web/controllers"
	"go-web/db"
	"go-web/models"
	"go-web/utils"
	"strconv"
	"strings"
	"time"

	"github.com/astaxie/beego"
)

type ArticleController struct {
	beego.Controller
}

// 列表
func (c *ArticleController) Get() {
	id, ok := GetUserIdBySessionA(c)
	if !ok {
		c.Redirect("/", 302)
		return
	}
	c.Data["Id"] = id
	c.Data["SmallVal"] = getSmallListValue()
	c.Data["BigList"] = getBigListValue()
	c.TplName = "admin/article.html"
}

func getBigListValue() *controllers.BigclassList {
	var AllBigClissesValue controllers.BigclassList
	AllBigClissesValue = append(AllBigClissesValue, models.Bigclass{Id: 0, Name: "所有", Order: 0})
	for _, v := range controllers.AllBigClisses {
		AllBigClissesValue = append(AllBigClissesValue, v)
	}

	return &AllBigClissesValue

}
func getSmallListValue() map[int]string {
	mis := map[int]string{}
	for _, v := range controllers.NavigationBar {
		var valsmall string
		valsmall += `<option value="0">所有</option>`
		if v.Scs.Len() > 0 {
			for _, vb := range v.Scs {
				valsmall += fmt.Sprintf(`<option value="%d">%s</option>`, vb.Id, vb.Name)
			}
			mis[v.Bc.Id] = valsmall
		}
	}
	return mis
}

func getSmallListValue1() map[int]string {
	mis := map[int]string{}
	for _, v := range controllers.NavigationBar {
		if v.Scs.Len() > 0 {
			var valsmall string
			for _, vb := range v.Scs {
				valsmall += fmt.Sprintf(`<option value="%d">%s</option>`, vb.Id, vb.Name)
			}
			mis[v.Bc.Id] = valsmall
		}
	}
	return mis
}

// 添加
func (c *ArticleController) Add() {
	id, ok := GetUserIdBySessionA(c)
	if !ok {
		c.Redirect("/", 302)
		return
	}
	c.Data["Id"] = id
	c.Data["SmallVal"] = getSmallListValue1()
	c.Data["BigList"] = controllers.AllBigClisses
	c.TplName = "admin/article_add.html"
}
func GetUserIdBySessionA(c *ArticleController) (int, bool) {
	str := c.Ctx.Input.Session(SessionKey)
	if str == nil {
		return 0, false
	}
	strs := strings.Split(str.(string), ":")
	if strs == nil || len(strs) != 4 {
		return 0, false
	}
	id, err := strconv.Atoi(strs[1])
	if err != nil {
		return 0, false
	}
	return id, true
}
func (c *ArticleController) CheckTitle() {
	title := c.GetString("title")
	bid, _ := c.GetInt("bid")
	sid, _ := c.GetInt("sid")
	if title == "" {
		c.Ctx.ResponseWriter.Write(utils.JsonToBytes(2, 0, "")) //无效的用户
		return
	}
	if bid == 0 || bid > len(controllers.AllBigClisses) {
		c.Ctx.ResponseWriter.Write(utils.JsonToBytes(3, 0, "")) //参数错误
		return
	}
	if sid < 0 || sid > len(controllers.AllSmallClassList) {
		c.Ctx.ResponseWriter.Write(utils.JsonToBytes(3, 0, "")) //参数错误
		return
	}
	detail := &models.Detail{}
	ok, _ := db.Mysql.Where("Title=? and Bigclassid =?  and Smallclassid=?", title, bid, sid).Get(detail)
	if !ok {
		c.Ctx.ResponseWriter.Write(utils.JsonToBytes(0, 0, "")) //已经存在标题
	} else {
		c.Ctx.ResponseWriter.Write(utils.JsonToBytes(1, 0, "")) //不存在标题
	}
}
func GetBetweenStr(str, start, end string) string {
	n := strings.Index(str, start)
	if n == -1 {
		return ""
	}
	str = string([]byte(str)[n:])
	m := strings.Index(str, end)
	if m == -1 {
		return ""
	}
	str = string([]byte(str)[len(start)-11 : m])
	return str
}

//添加一条新闻
//param [bid int](bigclassid)
//param [sid int](smallclassid)
//param [title string](标题)
//param [author string](作者)
//param [origin string](来源)
//param [context string](内容)
func (c *ArticleController) AddNew() {
	id, ok := GetUserIdBySessionA(c)
	if !ok || id <= 0 {
		c.Ctx.ResponseWriter.Write(utils.JsonToBytes(2, 0, "")) //无效的用户
		return
	}
	user := GetOneuser(id)
	if user == nil {
		c.Ctx.ResponseWriter.Write(utils.JsonToBytes(4, 0, "")) //无效的用户
		return
	}
	bid, _ := c.GetInt("bid")
	if bid == 0 || bid > len(controllers.AllBigClisses) {
		c.Ctx.ResponseWriter.Write(utils.JsonToBytes(8, 0, "")) //参数错误
		return
	}
	bname := controllers.AllBigClisses[bid-1]
	sid, _ := c.GetInt("sid")
	var sname *models.Smallclass
	if sid > 0 && sid <= len(controllers.AllSmallClassList) {
		sname = &controllers.AllSmallClassList[sid-1]
	}
	title := c.GetString("title")
	author := c.GetString("author")
	origin := c.GetString("origin")
	context := c.GetString("context")
	//lunbotu := c.GetString("lunbotu")
	nowdatestr := c.GetString("datenow")
	hitcountstr := c.GetString("hitscount")
	if title == "" || author == "" || origin == "" || context == "" {
		c.Ctx.ResponseWriter.Write(utils.JsonToBytes(7, 0, "")) //参数错误
		return
	}
	bexitdetail := models.Detail{}
	ok, err := db.Mysql.Where("title=? and Bigclassid =?  and Smallclassid=?", title, bid, sid).Get(&bexitdetail)
	if ok {
		c.Ctx.ResponseWriter.Write(utils.JsonToBytes(12, 0, "")) //已存在
		return
	}
	if err != nil {
		c.Ctx.ResponseWriter.Write(utils.JsonToBytes(13, 0, "")) //未知错误
		return
	}
	var url string
	if controllers.AllBigClisses.GetNameById(bid) == "实事时评" && controllers.AllSmallClassList.GetNameById(sid) == "社会实践" {
		url = GetBetweenStr(context, "<img src=\"/uploadfile", "\" title=")
	}

	timenow, err := time.ParseInLocation("2006-01-02 15:04:05", nowdatestr, time.Now().Location())
	if err != nil {
		timenow = time.Now()
	}
	hitcount, _ := strconv.Atoi(hitcountstr)
	if hitcount < 0 {
		hitcount = 0
	}
	detail := &models.Detail{
		Title:          title,
		Context:        context,
		Updatetime:     timenow,
		Createuserid:   user.Id,
		Createusername: user.Username,
		Hits:           hitcount,
		Bigclassid:     bid,
		Bigclassname:   bname.Name,
		Origin:         origin,
		Author:         author,
	}
	if sname != nil {
		detail.Smallclassid = sid
		detail.Smallclassname = sname.Name
	}
	if url != "" {
		detail.Haspic = 1
	}
	sess := db.Mysql.NewSession()
	defer sess.Close()
	sess.Begin()
	rows, err := sess.InsertOne(detail)
	if rows != 1 || err != nil {
		sess.Rollback()
		c.Ctx.ResponseWriter.Write(utils.JsonToBytes(3, 0, "")) //插入失败
	} else {
		if url != "" {
			lbt := models.Carousel{Url: url, Articleid: detail.Id, Updatetime: time.Now(), Articlename: title}
			sess.InsertOne(&lbt)
		}
		sess.Commit()
		InsertOperationLog(c.Ctx, id, detail.Id, L_AddArtice)
		c.Ctx.ResponseWriter.Write(utils.JsonToBytes(1, 0, "")) //插入成功
	}
}

func GetDetailList(rets []map[string][]byte, ds *[]models.Detail) {
	ids := make([]int, len(rets))
	for k, v := range rets {
		ids[k], _ = strconv.Atoi(utils.BytesToString(v["id"]))
	}
	db.Mysql.Select("id,title,updatetime,bigclassname,smallclassname,author,origin,hits").In("id", ids).Desc("updatetime").Find(ds)
	for k, v := range *ds {
		(*ds)[k].Context = v.Updatetime.Format("2006-01-02 15:04:05")
	}
}

// 修改
func (c *ArticleController) Edit() {
	Id, _ := c.GetInt(":id")
	detail := &models.Detail{Id: Id}
	ok, _ := db.Mysql.Get(detail)
	if !ok {
		c.Redirect("/admin/article", 302)
		return
	}
	times := detail.Updatetime.Format("2006-01-02 15:04:05")
	c.Data["Id"] = Id
	c.Data["Detail"] = detail
	c.Data["Times"] = times
	c.Data["SmallVal"] = getSmallListValue1()
	c.Data["BigList"] = controllers.AllBigClisses
	c.TplName = "admin/article_edit.html"
}

func (c *ArticleController) GetList() {
	start, _ := c.GetInt("s")
	if start < 1 {
		start = 1
	}
	count, _ := c.GetInt("c")
	name := c.GetString("n")
	if count == 0 {
		c.Ctx.ResponseWriter.Write(utils.JsonToBytes(2, 0, "")) //无效的参数
		return
	}
	bid, _ := c.GetInt("b")
	sid, _ := c.GetInt("sm")
	if bid < 0 || sid < 0 {
		c.Ctx.ResponseWriter.Write(utils.JsonToBytes(3, 0, "")) //无效的参数
		return
	}
	details := &models.Detail{}
	var CountDetails int64
	var err error
	if bid == 0 {
		if name == "" {
			CountDetails, err = db.Mysql.Where("bigclassid > 0").Count(details)
		} else {
			CountDetails, err = db.Mysql.Where(fmt.Sprintf("Title like '%%%s%%'", name)).Count(details)
		}
	} else {
		if name == "" {
			if sid == 0 {
				CountDetails, err = db.Mysql.Where("Bigclassid = ?", bid).Count(details)
			} else {
				CountDetails, err = db.Mysql.Where("Bigclassid = ? And Smallclassid = ?", bid, sid).Count(details)
			}
		} else {
			if sid == 0 {
				CountDetails, err = db.Mysql.Where(fmt.Sprintf("Bigclassid = ? And Title like '%%%s%%'", name), bid).Count(details)
			} else {
				CountDetails, err = db.Mysql.Where(fmt.Sprintf("Bigclassid = ? And Smallclassid = ? And  Title like '%%%s%%'", name), bid, sid).Count(details)
			}
		}
	}
	if err != nil {
		c.Ctx.ResponseWriter.Write(utils.JsonToBytes(0, 0, err)) //查询错误
		return
	}
	if CountDetails == 0 {
		c.Ctx.ResponseWriter.Write(utils.JsonToBytes(1, 0, "")) //没有数据
		return
	}
	ds := make([]models.Detail, 0)
	startindex := (start - 1) * count
	var rets []map[string][]byte
	if bid == 0 {
		if name == "" {
			rets, err = db.Mysql.Query("SELECT id FROM detail ORDER BY updatetime desc limit ?,?", startindex, count)
		} else {
			rets, err = db.Mysql.Query(fmt.Sprintf("SELECT id FROM detail WHERE title LIKE '%%%s%%' ORDER BY `updatetime` desc limit ?,?", name), startindex, count)
		}
	} else {
		if name == "" {
			if sid == 0 {
				rets, err = db.Mysql.Query("SELECT id FROM detail where BigClassId= ? ORDER BY `updatetime` desc limit ?,?", bid, startindex, count)
			} else {
				rets, err = db.Mysql.Query("SELECT id FROM detail WHERE BigClassId= ? And smallclassid=? ORDER BY `updatetime` desc limit ?,?", bid, sid, startindex, count)
			}
		} else {
			if sid == 0 {
				rets, err = db.Mysql.Query(fmt.Sprintf("SELECT id FROM detail WHERE  BigClassId= ? And title LIKE '%%%s%%' ORDER BY `updatetime` desc limit ?,?", name), bid, startindex, count)
			} else {
				rets, err = db.Mysql.Query(fmt.Sprintf("SELECT id FROM detail WHERE  BigClassId= ? And smallclassid=? And title LIKE '%%%s%%' ORDER BY `updatetime` desc limit ?,?", name), bid, sid, startindex, count)
			}
		}
	}
	GetDetailList(rets, &ds)
	if err == nil {
		c.Ctx.ResponseWriter.Write(utils.JsonToBytes(1, int(CountDetails), ds)) //OK
	} else {
		c.Ctx.ResponseWriter.Write(utils.JsonToBytes(0, 0, "")) //查询错误
	}
}

//修改一条新闻
//param [aid int](文章ID)
//param [bid int](bigclassid)
//param [sid int](smallclassid)
//param [title string](标题)
//param [author string](作者)
//param [origin string](来源)
//param [context string](内容)
func (c *ArticleController) EditNew() {
	id, ok := GetUserIdBySessionA(c)
	if !ok || id <= 0 {
		c.Ctx.ResponseWriter.Write(utils.JsonToBytes(2, 0, "")) //无效的用户
		return
	}
	user := GetOneuser(id)
	if user == nil {
		c.Ctx.ResponseWriter.Write(utils.JsonToBytes(4, 0, "")) //无效的用户
		return
	}
	bid, _ := c.GetInt("bid")
	if bid <= 0 || bid > len(controllers.AllBigClisses) {
		c.Ctx.ResponseWriter.Write(utils.JsonToBytes(8, 0, "")) //参数错误
		return
	}
	aid, _ := c.GetInt("aid")
	if aid <= 0 {
		c.Ctx.ResponseWriter.Write(utils.JsonToBytes(8, 0, "")) //参数错误
		return
	}
	detail := &models.Detail{Id: aid}
	ok, _ = db.Mysql.Get(detail)
	if !ok {
		c.Ctx.ResponseWriter.Write(utils.JsonToBytes(8, 0, "")) //参数错误
		return
	}
	bname := controllers.AllBigClisses[bid-1]
	sid, _ := c.GetInt("sid")
	var sname *models.Smallclass
	if sid > 0 && sid <= len(controllers.AllSmallClassList) {
		sname = &controllers.AllSmallClassList[sid-1]
	} else {
		sid = 0
	}
	title := c.GetString("title")
	author := c.GetString("author")
	origin := c.GetString("origin")
	context := c.GetString("context")
	//lunbotu := c.GetString("lunbotu")
	nowdatestr := c.GetString("datenow")
	hitcountstr := c.GetString("hitscount")
	if title == "" || author == "" || origin == "" || context == "" {
		c.Ctx.ResponseWriter.Write(utils.JsonToBytes(7, 0, "")) //参数错误
		return
	}
	bexitdetail := models.Detail{}
	ok, err := db.Mysql.Where("title=? and Bigclassid =?  and Smallclassid=?", title, bid, sid).Get(&bexitdetail)
	if ok && bexitdetail.Id != detail.Id {
		c.Ctx.ResponseWriter.Write(utils.JsonToBytes(12, 0, "")) //已存在
		return
	}
	if err != nil {
		c.Ctx.ResponseWriter.Write(utils.JsonToBytes(13, 0, "")) //未知错误
		return
	}
	var url string
	if controllers.AllBigClisses.GetNameById(bid) == "新闻中心" && controllers.AllSmallClassList.GetNameById(sid) == "学院新闻" {
		url = GetBetweenStr(context, "<img src=\"/uploadfile", "\" title=")
	}

	timenow, err := time.ParseInLocation("2006-01-02 15:04:05", nowdatestr, detail.Updatetime.Location())
	if err != nil {
		timenow = time.Now()
	}
	hitcount, _ := strconv.Atoi(hitcountstr)
	if hitcount < 0 {
		hitcount = 0
	}
	oldhaspic := detail.Haspic
	detail.Author = author
	detail.Bigclassid = bid
	detail.Bigclassname = bname.Name
	detail.Origin = origin
	detail.Context = context
	detail.Title = title
	detail.Updatetime = timenow
	detail.Hits = hitcount
	if sname != nil {
		detail.Smallclassid = sid
		detail.Smallclassname = sname.Name
	}
	if url != "" {
		detail.Haspic = 1
	} else {
		detail.Haspic = 0
	}
	sess := db.Mysql.NewSession()
	defer sess.Close()
	sess.Begin()
	rows, err := sess.Id(detail.Id).MustCols("haspic").Update(detail)
	if rows != 1 || err != nil {
		sess.Rollback()
		fmt.Println(rows, err)
		c.Ctx.ResponseWriter.Write(utils.JsonToBytes(3, 0, "")) //插入失败
	} else {
		if url != "" {
			if oldhaspic == 1 {
				lbt := models.Carousel{Url: url, Updatetime: time.Now(), Articlename: title}
				db.Mysql.Where("articleid=?", detail.Id).Update(&lbt)
			} else {
				lbt := models.Carousel{Url: url, Articleid: detail.Id, Updatetime: time.Now(), Articlename: title}
				db.Mysql.InsertOne(&lbt)
			}
		} else {
			if oldhaspic == 1 {
				lbt := models.Carousel{}
				db.Mysql.Where("articleid=?", detail.Id).Delete(lbt)
			}
		}
		sess.Commit()
		InsertOperationLog(c.Ctx, id, detail.Id, L_EditArtice)
		c.Ctx.ResponseWriter.Write(utils.JsonToBytes(1, 0, "")) //插入成功
	}
}

//删除一条新闻
//param [id int](新闻Id)
func (c *ArticleController) DeleteArticle() {
	id, err := c.GetInt("id")
	if id <= 0 {
		c.Ctx.ResponseWriter.Write(utils.JsonToBytes(0, 0, "")) //无效的新闻ID
		return
	}
	detail := &models.Detail{}
	rows, err := db.Mysql.Id(id).Delete(detail)
	if rows != 1 || err != nil {
		c.Ctx.ResponseWriter.Write(utils.JsonToBytes(2, 0, "")) //删除失败
	} else {
		lbt := models.Carousel{}
		db.Mysql.Where("articleid = ?", id).Delete(lbt)
		InsertOperationLog(c.Ctx, 0, id, L_DeleteArtice)
		c.Ctx.ResponseWriter.Write(utils.JsonToBytes(1, 0, "")) //删除成功
	}
}

/*
func (c *ArticleController) Lunbotu() {
	id, _ := c.GetInt(":id")
	if id < 1 || id > 4 {
		c.Ctx.ResponseWriter.Write(utils.JsonToBytes(12, 0, "")) //上传失败
		return
	}
	name := "img_" + strconv.Itoa(id)
	f, h, err := c.GetFile(name)
	if err != nil && f != nil {
		f.Close()
		return
	}
	if h == nil {
		return
	}
	dname := c.GetString("dname")
	if len(dname) >= 255 {
		c.Ctx.ResponseWriter.Write(utils.JsonToBytes(2, 0, "")) //上传失败
		return
	}
	datePath := time.Now().Format("2006-01-02/15-04-05-999999999/")
	dirPath := "assets/img/" + strconv.Itoa(id) + datePath
	err = os.MkdirAll(dirPath, 0777)
	if err != nil {
		c.Ctx.ResponseWriter.Write(utils.JsonToBytes(42, 0, "")) //上传失败
		return
	}
	dirPath += h.Filename
	err = c.SaveToFile(name, dirPath)
	if err != nil {
		c.Ctx.ResponseWriter.Write(utils.JsonToBytes(13, 0, "")) //上传失败
		return
	} else {
		carousel := &models.Carousel{}
		ok, _ := db.Mysql.Id(id).Get(carousel)
		if ok {
			carousel.Url = dname
			carousel.Url = dirPath
			rows, err := db.Mysql.Id(id).Update(carousel)
			if rows != 1 || err != nil {
				c.Ctx.ResponseWriter.Write(utils.JsonToBytes(14, 0, "")) //上传失败
			} else {
				c.Ctx.ResponseWriter.Write(utils.JsonToBytes(1, 0, "")) //上传成功
			}
		} else {
			carousel.Url = dname
			carousel.Id = id
			carousel.Pic = dirPath
			rows, err := db.Mysql.InsertOne(carousel)
			if rows != 1 || err != nil {
				c.Ctx.ResponseWriter.Write(utils.JsonToBytes(15, 0, "")) //上传失败
			} else {
				InsertOperationLog(c.Ctx, 0, id, L_ChanetCarousel)
				c.Ctx.ResponseWriter.Write(utils.JsonToBytes(1, 0, "")) //上传成功
			}
		}
	}
}*/
